<template>
  <div>
    <el-card>
      <div slot="header">
        <el-breadcrumb separator-class="el-icon-arrow-right">
          <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item>个人设置</el-breadcrumb-item>
        </el-breadcrumb>
      </div>
      <div>
        <el-row>
          <el-col :span="12">
            <el-form
              :model="user"
              :rules="rules"
              ref="ruleForm"
              label-width="80px"
            >
              <el-form-item label="编号">
                {{ user.id }}
              </el-form-item>
              <el-form-item label="手机">
                {{ user.mobile }}
              </el-form-item>
              <el-form-item label="用户姓名" prop="name">
                <el-input v-model="user.name"></el-input>
              </el-form-item>
              <el-form-item label="个人介绍">
                <el-input type="textarea" v-model="user.intro"></el-input>
              </el-form-item>
              <el-form-item label="邮箱" prop="email">
                <el-input v-model="user.email"></el-input>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="onUpdateUser"
                  >保存设置</el-button
                >
              </el-form-item>
            </el-form>
          </el-col>
          <el-col :offset="4" :span="8">
            <label for="fo">
              <el-avatar
                class="head"
                shape="square"
                :size="200"
                :src="user.photo"
              ></el-avatar>
            </label>
            <div class="text" @click="$refs.File.click()">点击修改头像</div>
            <input
              type="file"
              id="fo"
              ref="File"
              @change="onFileChange"
              hidden
            />
          </el-col>
        </el-row>
      </div>
    </el-card>
    <!-- 对话框 -->
    <el-dialog
      title="修改头像"
      :visible.sync="dialogVisible"
      width="30%"
      :before-close="handleClose"
      :append-to-body="true"
      @opened="onDialogOpened"
      @closed="onDialogClosed"
    >
      <div class="preview-image-wrap">
        <img :src="previewImage" ref="preview-image" class="preview-image" />
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="onUpdatePhto" :loading="loading"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import bus from "@/utils/bus";
//引入图片裁剪 样式
import "cropperjs/dist/cropper.css";
import Cropper from "cropperjs";
import { apiGetUserProfile, apiupdateUserPhoto } from "@/api/user";
// const image = document.getElementById('image'); //获取图片DOM节点    const image = this.$refs['preview-image']
//const image = this.$refs['preview-image']
// const cropper = new Cropper(image, { //初始化裁切器       img必须是可见状态才能完成初始化
//   aspectRatio: 16 / 9, //裁切框的比例
// });
export default {
  name: "setting",
  created() {
    this.loadUser();
  },

  data() {
    return {
      dialogVisible: false,
      previewImage: "", //预览图片
      cropper: null, //裁切期实例
      loading: false,
      user: {
        email: "1882646@123.qq", //邮箱
        id: 15, //编号
        intro: "嘎嘎嘎嘎", //介绍
        mobile: 18804468201, //手机
        name: "名称王棋名称王棋名棋", //名称
        photo: "https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg" //头像
      },
      rules: {
        name: [
          { required: true, message: "请输入活动名称", trigger: "blur" },
          { min: 3, max: 10, message: "长度在 3 到 10 个字符", trigger: "blur" }
        ],
        email: [
          { required: true, message: "请输入邮箱地址", trigger: "blur" },
          {
            type: "email",
            message: "请输入正确的邮箱地址",
            trigger: ["blur", "change"]
          }
        ]
      }
    };
  },
  methods: {
    loadUser() {
      apiGetUserProfile().then(res => {
        //获取到了当前登陆用户的信息
        console.log(res);
      });
    },
    //上传图片事件
    onFileChange() {
      //处理图片预览
      const File = this.$refs.File;
      const blobData = window.URL.createObjectURL(File.files[0]);
      console.log(blobData);
      this.previewImage = blobData;

      // console.log(File.files[0])
      this.$refs.File.value = ""; //解决选择相同文件不触发 change事件的问题
      this.dialogVisible = true; //展示弹出对话框
    },
    //对话框完全打开触发 图片裁剪
    onDialogOpened() {
      const image = this.$refs["preview-image"];
      this.cropper = new Cropper(image, {
        //初始化裁切器       img必须是可见状态才能完成初始化
        aspectRatio: 1, //裁切比例
        viewMode: 1, //裁切框 不可以延申到画布外
        dragMode: "none", //不可以移动画布和
        background: false,
        cropBoxResizable: false //裁剪框可调整大小
      });
    },
    //对话框关闭销毁裁切器  解决裁切器不更新问题
    onDialogClosed() {
      this.cropper.destroy();
    },
    //获取裁切结果 并更新头像
    onUpdatePhto() {
      this.cropper.getCroppedCanvas().toBlob(file => {
        console.log(file); //获取裁切图片返回的对象
        const fd = new FormData();
        //有接口在请求成功后操作
        this.user.photo = window.URL.createObjectURL(file);
        fd.append("后台提供的参数名", file);
        //
        apiupdateUserPhoto(fd).then(res => {
          //关闭弹出层
          this.dialogVisible = false;
          //更新头像
          this.user.photo = window.URL.createObjectURL(file);
        });
        this.dialogVisible = false;
      });
    },
    //保存修改头像和名称
    onUpdateUser() {
      this.$refs["ruleForm"].validate((val, err) => {
        if (val) {
          bus.$emit("update-user", this.user);
          this.$message({
            message: "恭喜你，保存成功",
            type: "success",
            duration: 1000
          });
        }
        return;
      });
    },
    //对话框
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then(_ => {
          done();
        })
        .catch(_ => {});
    }
  }
};
</script>
<style lang="less" scoped>
.head {
  border: 1px dashed rgb(109, 102, 102);
}
.text {
  margin-left: 48px;
  color: rgb(133, 133, 133);
  font-size: 15px;
}
.text:hover {
  color: #409eff;
}
.preview-image-wrap > .preview-image {
  display: block;
  max-width: 100%;
}
</style>
